<template>
	<xn-form-container title="短信发送" :width="400" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-row :gutter="24">
			<a-col :span="24">
				<a-spin :spinning="uploadLoading">
					<a-upload-dragger
						ref="uploadRef"
						:before-upload="handleBeforeUpload"
						v-model:file-list="fileList"
						:show-upload-list="true"
						:headers="headers"
						accept=".xlsx, .xls, .csv"
						:auto-upload="false"
						multiple
					>
						<p class="ant-upload-drag-icon">
							<inbox-outlined></inbox-outlined>
						</p>
						<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
						<p class="ant-upload-hint">支持单个上传</p>
					</a-upload-dragger>
					<a-button type="link" @click="download">点击下载短信发送导入模版</a-button>
					<a-form class="mt-2" ref="formRef" :model="formData" :rules="rules" label-align="right">
						<a-form-item label="短信模版" name="templateCode">
							<a-select v-model:value="formData.templateCode" placeholder="请选择短信模版">
								<a-select-option
									v-for="option in templateList"
									:key="option.templateCode"
									:value="option.templateCode"
									:label="option.templateName"
								>
									{{ option.templateName }}
								</a-select-option>
							</a-select>
						</a-form-item>
						<a-form-item label="路由顺序" name="supplierOrder" :rules="rules.supplierOrder">
							<a-select v-model:value="selectedSupplier" placeholder="请选择路由" @change="addSupplier">
								<a-select-option
									v-for="option in availableSuppliers"
									:key="option.supplierCode"
									:value="option.supplierCode"
								>
									{{ option.supplierName }}
								</a-select-option>
							</a-select>
							<!--							<a-select v-model:value="formData.templateCode" placeholder="请选择短信签名">-->
							<!--								<a-select-option-->
							<!--									v-for="option in signList"-->
							<!--									:key="option.signCode"-->
							<!--									:value="option.signCode"-->
							<!--									:label="option.signContent"-->
							<!--								>-->
							<!--									{{ option.signContent }}-->
							<!--								</a-select-option>-->
							<!--							</a-select>-->
							<VueDraggable v-model="supplierList" @end="onEnd">
								<div v-for="item in supplierList" :key="item.id" class="supplier-item">
									<a-tag style="cursor: pointer">{{ item.supplierName }}</a-tag>
									<a-button danger type="link" @click="removeSupplier(item.supplierCode)">x</a-button>
								</div>
							</VueDraggable>
						</a-form-item>
						<a-row>
							<CompanySelect item-type="project" colSpan="24" @change-company-select-event="changeCompanySelectEvent" />
						</a-row>
						<a-form-item label="签名城市" name="signCity">
							<a-select v-model:value="formData.signCity" placeholder="请选择签名所属城市">
								<a-select-option
									v-for="item in [{ name: '天津' }, { name: '盐城' }]"
									:key="item.name"
									:value="item.name"
									>{{ item.name }}
								</a-select-option>
							</a-select>
						</a-form-item>
						<a-form-item label="批次名称" name="batchName">
							<a-input v-model:value="formData.batchName" placeholder="请输入批次名称" />
						</a-form-item>
						<a-form-item label="名单过滤" name="filter">
							<a-checkbox v-model:checked="filterChecked" disabled>投诉用户</a-checkbox>
						</a-form-item>
						<a-form-item label="项目手机号过滤" name="filter">
							<a-checkbox v-model:checked="projectBlackListChecked">项目手机号过滤</a-checkbox>
						</a-form-item>
					</a-form>
				</a-spin>
			</a-col>
		</a-row>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>
<script setup>
	import tool from '@/utils/tool'
	import fileApi from '@/api/tjzy/file/fileApi'
	import downloadUtil from '@/utils/downloadUtil'
	import { message, notification } from 'ant-design-vue'
	import smsBatchApi from '@/api/tjzy/sms/smsBatchApi'
	import CompanySelect from '@/components/Tjzy/Company/CompanySelect.vue'
	import smsTemplateApi from '@/api/tjzy/sms/smsTemplateApi'
	import { VueDraggable } from 'vue-draggable-plus'
	import supplierApi from '@/api/tjzy/supplier/supplierApi'

	const emit = defineEmits({ successful: null })
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const filterChecked = true
	const projectBlackListChecked = ref(false) //项目手机号过滤
	const visible = ref(false)
	const uploadLoading = ref(false)
	const submitLoading = ref(false)
	const fileList = ref([])
	const uploadRef = ref()
	const templateList = ref([])
	const supplierList = ref([])
	const availableSuppliers = ref([]) // 可用的供应商列表
	const selectedSupplier = ref(null) // 当前选择的供应商
	const signList = ref()
	const formRef = ref()
	const formData = ref({
		templateCode: undefined,
		projectCode: undefined,
		signCity: undefined,
		batchName: undefined,
		supplierOrder: undefined,
		filter: filterChecked,
		projectBlackList: projectBlackListChecked
	})
	const rules = {
		templateCode: [{ required: true, message: '短信模版不能为空', trigger: 'change' }],
		projectCode: [{ required: true, message: '项目代码不能为空', trigger: 'blur' }],
		supplierOrder: [{ required: true, message: '至少选择一个供应商', trigger: 'blur' }],
		signCity: [{ required: true, message: '批次名称不能为空', trigger: 'blur' }],
		batchName: [{ required: true, message: '批次名称不能为空', trigger: 'blur' }],
		filter: [{ required: true, message: '', trigger: 'blur' }]
	}

	// 打开抽屉
	const openUpload = () => {
		visible.value = true
		smsTemplateApi.list().then((res) => {
			templateList.value = res
		})
		supplierApi.list().then((res) => {
			availableSuppliers.value = res // 获取所有可用的供应商
			supplierList.value = [] // 初始化拖拽列表为空
			formData.value.supplierOrder = supplierList.value.map((item) => item.supplierCode).join(',')
		})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		// 重置弹框数据
		fileList.value = []
		formData.value = {
			templateCode: undefined,
			projectCode: undefined,
			batchName: undefined,
			supplierOrder: undefined,
			filter: filterChecked,
			projectBlackList: projectBlackListChecked.value
		}
		selectedSupplier.value = null
		emit('successful')
	}

	const handleBeforeUpload = () => {
		console.log('beforeUpload')
		return false
	}

	const addSupplier = (supplierCode) => {
		console.log('availableSuppliers', availableSuppliers, supplierCode)
		const selectedSupplier = availableSuppliers.value.find((s) => s.supplierCode === supplierCode)
		signList.value = JSON.parse(selectedSupplier.sign)
		console.log(signList.value)
		if (selectedSupplier && !supplierList.value.some((s) => s.supplierCode === supplierCode)) {
			supplierList.value.push(selectedSupplier)
			formData.value.supplierOrder = supplierList.value.map((item) => item.supplierCode).join(',')
		} else {
			message.warning('该供应商已添加')
		}
	}

	const removeSupplier = (supplierCode) => {
		if (supplierList.value.length === 1) {
			message.warning('至少需要保留一个供应商')
			return
		}
		supplierList.value = supplierList.value.filter((item) => item.supplierCode !== supplierCode)
		formData.value.supplierOrder = supplierList.value.map((item) => item.supplierCode).join(',')
	}

	const onEnd = () => {
		formData.value.supplierOrder = supplierList.value.map((item) => item.supplierCode).join(',')
	}

	const changeCompanySelectEvent = (val) => {
		formData.value.projectCode = val.projectCode
	}

	const onSubmit = () => {
		console.log('projectBlackListChecked', projectBlackListChecked.value, 'formdata', formData.value.projectBlackList)
		if (fileList.value.length > 0) {
			formRef.value
				.validate()
				.then(() => {
					uploadLoading.value = true
					submitLoading.value = true
					const fileData = new FormData()
					fileData.append('multipartFile', fileList.value[0].originFileObj)
					fileData.append('smsBatchAddBo', new Blob([JSON.stringify(formData.value)], { type: 'application/json' }))
					smsBatchApi
						.importExcel(fileData)
						.then((res) => {
							emit('successful')
							notification.success({
								description: res,
								placement: 'top'
							})
						})
						.finally(() => {
							uploadLoading.value = false
							submitLoading.value = false
						})
					onClose()
				})
				.catch((err) => {
					message.error('表单校验失败')
				})
		}
	}

	const download = () => {
		fileApi.download('短信发送模版.xlsx').then((res) => {
			downloadUtil.resultDownload(res)
		})
	}

	defineExpose({
		openUpload
	})
</script>
